package com.wangjiyuan.shiwupai.ui.fragment.guangchi;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.wangjiyuan.shiwupai.R;
import com.wangjiyuan.shiwupai.adapter.GuangChiAdapter;
import com.wangjiyuan.shiwupai.base.BaseFragment;
import com.wangjiyuan.shiwupai.base.base_map.BaseMap;
import com.wangjiyuan.shiwupai.bean.guangchi.categorie.CategoriesBean;
import com.wangjiyuan.shiwupai.ui.fragment.guangchi.pager.PagerFragment;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 */
public class GuangChiFragment extends BaseFragment implements GuangChiContract.GuangChiView {

    private TabLayout mTab;
    private ViewPager mViewPager;
    private List<PagerFragment> mList;
    private List<CategoriesBean> mTitle;
    private PagerAdapter adapter;

    public GuangChiFragment() {
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_guang_chi, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mTab = (TabLayout) view.findViewById(R.id.tab);
        mViewPager = (ViewPager) view.findViewById(R.id.view_pager);
        mTab.setupWithViewPager(mViewPager);

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mList = new ArrayList<>();
        mTitle = new ArrayList<>();
        adapter = new GuangChiAdapter(getActivity().getSupportFragmentManager(),
                mList, mTitle);
        mViewPager.setAdapter(adapter);
        mViewPager.setOffscreenPageLimit(0);
        GuangChiPresenter presenter = new GuangChiPresenter(this);
        Map<String, String> map = BaseMap.baseMap();
        presenter.getTab(map);
    }

    @Override
    public void getTab(List<CategoriesBean> categoriesBeanList) {
        mTitle.clear();
        mTitle.addAll(categoriesBeanList);
        addFragment();
    }

    private void addFragment() {
        for (CategoriesBean bean : mTitle) {
            PagerFragment pager = PagerFragment.
                    newInstance(1, bean.getId());
            mList.add(pager);
            adapter.notifyDataSetChanged();
        }
    }
}
